from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .serializers import CryptoSerializer
from .utils import CryptoUtils


@api_view(["POST"])
def crypto(request):
    """
    加密/解密API
    """
    # 使用序列化器验证输入数据
    serializer = CryptoSerializer(data=request.data)

    # 验证输入数据
    if not serializer.is_valid():
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # 获取验证后的数据
    text = serializer.validated_data['text']
    password = serializer.validated_data['password']
    action = serializer.validated_data['action']

    try:
        # 根据操作类型执行加密或解密
        if action == 'encrypt':
            result = CryptoUtils.encrypt(text, password)
        elif action == 'decrypt':
            result = CryptoUtils.decrypt(text, password)
        else:
            return Response({'error': '无效的操作类型'}, status=status.HTTP_400_BAD_REQUEST)

        # 返回成功响应
        return Response({'result': result}, status=status.HTTP_200_OK)

    except Exception as e:
        # 返回错误响应
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
